package Server

import (
	"fmt"

	"github.com/wzh200x/hyperNexus/hyperNexusModel"
)

func QueryModel[T any](modelName string, shareValue string, where string, args ...interface{}) (*T, error) {
	eModel := GDBApp.GetDBHelper().GetModelByName(modelName)
	if eModel != nil {
		e := hyperNexusModel.NewEntity(eModel).(*T)
		tName := eModel.TableName()
		if eModel.ShardConfig != nil {
			var err error
			tName, err = eModel.GetShardDataTabelName(shareValue)
			if err != nil {
				return nil, err
			}
		}
		err := GDBApp.GetDBHelper().Query(tName, e, where, args...)
		if err != nil {
			return nil, err
		}
		return e, nil
	}
	return nil, fmt.Errorf("model not found")
}

func QueryModelAll[T any](modelName string, shareValue string, where string, args ...interface{}) ([]*T, error) {
	eModel := GDBApp.GetDBHelper().GetModelByName(modelName)
	if eModel != nil {
		tName := eModel.TableName()
		if eModel.ShardConfig != nil {
			var err error
			tName, err = eModel.GetShardDataTabelName(shareValue)
			if err != nil {
				return nil, err
			}
		}
		var results []*T
		err := GDBApp.GetDBHelper().QueryAll(tName, &results, where, args...)
		if err != nil {
			return nil, err
		}
		return results, nil
	}
	return nil, fmt.Errorf("model not found")
}

func CreateModel[T any](modelName string, shareValue string) (*T, error) {
	eModel := GDBApp.GetDBHelper().GetModelByName(modelName)
	if eModel != nil {
		tName := eModel.TableName()
		if eModel.ShardConfig != nil {
			var err error
			tName, err = eModel.GetShardDataTabelName(shareValue)
			if err != nil {
				return nil, err
			}
		}
		e := hyperNexusModel.NewEntity(eModel).(*T)
		err := GDBApp.GetDBHelper().Create(tName, e)
		if err != nil {
			return nil, err
		}
		return e, nil
	}
	return nil, fmt.Errorf("model not found")
}

func UpdateModel[T any](modelName string, shareValue string, entity *T) error {
	eModel := GDBApp.GetDBHelper().GetModelByName(modelName)
	if eModel != nil {
		tName := eModel.TableName()
		if eModel.ShardConfig != nil {
			var err error
			tName, err = eModel.GetShardDataTabelName(shareValue)
			if err != nil {
				return err
			}
		}
		err := GDBApp.GetDBHelper().Update(tName, entity)
		if err != nil {
			return err
		}
		return nil
	}
	return fmt.Errorf("model not found")
}

func GetModelShareNum(modelName string, shareValue string) int {
	eModel := GDBApp.GetDBHelper().GetModelByName(modelName)
	if eModel != nil {
		return eModel.GetShardTableNum(shareValue)
	}
	return 0
}
